package com.ponxu.mb.web.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;

public class URLMappingFilter implements Filter {
	private static final Log LOG = LogFactory.getLog();
	private String urls = "/urls.properties";
	private Map<Pattern, String> urlPattern;

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		LOG.debug("----------URLMappingFilter begin----------");

		boolean processed = false;
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getServletPath();
		request.setAttribute("OldURI", uri);

		Iterator<Entry<Pattern, String>> it = urlPattern.entrySet().iterator();
		while (it.hasNext()) {
			Entry<Pattern, String> entry = it.next();
			Pattern key = entry.getKey();
			String value = entry.getValue();

			Matcher matcher = key.matcher(uri);
			if (matcher.find()) {
				processed = true;
				int c = matcher.groupCount();
				for (int i = 1; i <= c; i++) {
					value = value.replace("{" + i + "}", matcher.group(i));
				}
				LOG.debug("rewrite: %s", value);
				request.getRequestDispatcher(value).forward(request, response);
				break;
			}
		}

		if (!processed) {
			chain.doFilter(request, response);
		}

		LOG.debug("----------URLMappingFilter end----------");
	}

	public void init(FilterConfig fConfig) throws ServletException {
		urlPattern = new LinkedHashMap<Pattern, String>();
		InputStream in = URLMappingFilter.class.getResourceAsStream(urls);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			String line = null;
			while ((line = br.readLine()) != null) {
				int i = line.indexOf("=");
				if (!line.trim().startsWith("#") && i > 0) {
					String key = line.substring(0, i);
					String value = line.substring(i + 1);
					LOG.debug("%s=%s", key, value);
					Pattern p = Pattern.compile(key);
					urlPattern.put(p, value);
				}
			}

			br.close();
			in.close();
		} catch (IOException e) {
			LOG.error(urls, e);
		}
	}

	public void destroy() {
	}
}
